#ifndef SERIAL_PORT_H
#define SERIAL_PORT_H

#include <string>
#include <vector>
#include <stdexcept>
#include <functional>
#include <thread>
#include <atomic>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>

class serial_port {
public:
    using data_callback_t = std::function<void(const std::vector<uint8_t>&)>;

    serial_port(const std::string &port_name, int baud_rate = B115200, bool ctsrts = false);
    ~serial_port();

    void open_port();
    void close_port();
    void write_data(const std::vector<uint8_t> &data);
    void set_data_callback(data_callback_t callback);

private:
    std::string port_name;
    int baud_rate;
    bool ctsrts;
    int fd;
    termios tty;
    std::thread read_thread;
    std::atomic<bool> running;
    data_callback_t data_callback;

    void configure_port();
    void read_loop();
};

#endif // SERIAL_PORT_H
